﻿using Communication.Message.Buffer;
using Communication.Message.Osc;
using growatt.Message.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace growatt.Message.Osc
{
    public class SwitchIPMOS : OscChannelMessage
    {
        public SwitchIPMOS() : base(0x04)
        {
            try
            {
                this.sendBuffer = MessageBuffers.Buffer(3);
                this.receiveBuffer = MessageBuffers.DynamicBuffer(3);
                this.sendBuffer.WriteByte(byte.MaxValue);
                this.sendBuffer.WriteByte(this.fun);
                this.sendBuffer.WriteByte(0x04);
                byte b = OscUtils.Crc8(this.sendBuffer.Array(), this.sendBuffer.ReaderIndex(), this.sendBuffer.ReadableBytes());
                this.sendBuffer.WriteByte(b);
                var str = ConvertHelper.ByteToHexStr(sendBuffer.Array(), joinString: " ");
                Console.WriteLine(str + $"   长度{sendBuffer.Array().Length}");
                this.sendBuffer.MarkReaderIndex();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        /// <summary>
        /// 处理接收报文
        /// </summary>
        /// <returns></returns>
        protected override bool DealwithReceiveMsg()
        {
            byte @byte;
            byte b;
            if (this.receiveBuffer.ReadableBytes() == 3)
            {
                @byte = this.receiveBuffer.GetByte(this.receiveBuffer.ReaderIndex() + 2);
                b = OscUtils.Crc8(this.receiveBuffer.Array(), this.receiveBuffer.ReaderIndex(), 2);
                if (b == @byte) //回复帧
                {
                    if (Enum.IsDefined(typeof(OscErrorCode), (uint)this.receiveBuffer.GetByte(this.receiveBuffer.ReaderIndex() + 1)))
                    {
                        this.errorCode = (OscErrorCode)Enum.Parse(typeof(OscErrorCode), this.receiveBuffer.GetByte(this.receiveBuffer.ReaderIndex() + 1).ToString());
                    }
                    base.SetSuccess();
                    return true;
                }
            }
            return true;
        }

        // Token: 0x06000146 RID: 326 RVA: 0x00003BD4 File Offset: 0x00001DD4
        public override int GetCancelSendData(byte[] buffer, int offset)
        {
            return 0;
        }

        // Token: 0x0400004B RID: 75
        private int channelCount;
    }
}
